from string import Template
from BeautifulSoup import BeautifulStoneSoup
import re
from google.appengine.ext import db

class OutputTemplate():
	def __init__(self,TemplateDefFile):
				#Comment out the next 4 lines to run using the template files instead of the Datastore ones
				#Templates =  db.GqlQuery("SELECT * FROM DataStoreTemplate WHERE name=:1",TemplateDefFile.lower())
				#if Templates.count()==0:
				#	Templates = db.GqlQuery("SELECT * FROM DataStoreTemplate WHERE name=:1","default")
				#self. Definition = Templates[0].text
				#Uncomment the next line if you are running a local copy and have a Formats folder
				self.Definition = file(TemplateDefFile).read()
				self.Header = Template(re.search("<Header>(.*)</Header>.*<Body>",self.Definition,re.S).group(1))
				self.Body = Template(re.search("<Body>(.*)</Body>",self.Definition,re.S).group(1))
				self.Footer = Template(re.search("<Footer>(.*)</Footer>",self.Definition,re.S).group(1))
		
	def Generate(self,Header=None,Body=None,Footer=None):
		HeaderContents = self.Header.safe_substitute(Header).lstrip()
		FooterContents = self.Footer.safe_substitute(Footer).rstrip()
		Contents = []
		if Body != None:
			for Key in Body.keys():
				Contents.append(self.Body.safe_substitute(Body[Key]))
		self.LastGenerated = '%s%s%s'%(HeaderContents,''.join(Contents),FooterContents)
		return self.LastGenerated
	
	
class DataStoreTemplate(db.Model):
	name = db.StringProperty(required = True)
	text = db.TextProperty(required = True)